package com.cxl.kafka;

import com.alibaba.fastjson.JSON;
import com.cxl.entity.Log;
import com.cxl.entity.LogDoc;
import com.cxl.entity.User;
import com.cxl.morspository.MogoRspository;
import com.cxl.service.ILogService;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author: 20971
 * @time: 2022/3/16 9:44
 * @description:
 */
@Component
public class ConsumerKafka {

    @Autowired
    private ILogService iLogService;

    @Autowired
    private MogoRspository mogoRspository;

    @KafkaListener(topics = {"log"})
    public void conlistener(ConsumerRecord<String,String> consumerRecord, Acknowledgment acknowledgment) {
        String value = consumerRecord.value();
        //日志信息添加到数据库的同时
        User user = JSON.parseObject(value, User.class);
        Log log = new Log();
        log.setContent(user.toString());
        log.setCreated(new Date());
        iLogService.save(log);
        //添加到mongdb中
        LogDoc logDoc = new LogDoc();
        logDoc.setContent(user.toString());
        logDoc.setCreated(new Date());
        mogoRspository.save(logDoc);
        acknowledgment.acknowledge();
    }
}
